<?php
/**
 * DummyService.php
 * 文件描述 虚拟对象逻辑页
 * Created on 2020/8/31 18:35
 * Created by 刘小龙 595929049@qq.com
 */

namespace app\xiangji\services;



use app\common\caches\DummyCache;
use app\common\facades\auth\Auth;
use app\common\helpers\Response;
use app\common\models\DummyJotting;
use app\Request;
use app\xiangji\exception\BadRequestException;
use app\xiangji\exception\ModelNotFoundException;
use app\xiangji\exception\ServiceUnavailableException;
use Carbon\Carbon;
use think\facade\Db;

class DummyJottingService
{
    private $user;

    public function __construct()
    {
        $this->user = Auth::guard('api')->user();
    }

    public function fetch(Request $request)
    {
        if (!$this->user->dummy){
            throw new BadRequestException('请先创建虚拟对象', Response::HTTP_FORBIDDEN);
        }
        $model = $this->user->dummy->jottings();
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        return $model->field(['id', 'content', 'score', 'create_time', 'update_time'])->order('id', 'desc')->paginate(['list_rows' => $limit, 'page' => $page]);
    }

    public function show(int $id)
    {
        if (!$this->user->dummy){
            throw new BadRequestException('请先创建虚拟对象', Response::HTTP_FORBIDDEN);
        }
        return $this->user->dummy->jottings()->field(['id', 'content', 'score', 'create_time', 'update_time'])->find($id);
    }

    public function store(Request $request)
    {
        //校验字数：文字+表情不超过30
        $preg='/<img.*?\/emoji\/(\d{1,3})\.gif.*?>/is';
        if (mb_strlen(preg_replace($preg, 'q', $request->post('content', ''))) > 30){
            throw new BadRequestException('随笔不能超过30个字符');
        }
        // 需先创建虚拟对象
        if (!$this->user->dummy){
            throw new BadRequestException('请先创建虚拟对象', Response::HTTP_FORBIDDEN);
        }
        $times = DummyJotting::withTrashed() // 包括已删除的
            ->where('user_id', '=', $this->user->id)
            ->where('create_time', '>=', Carbon::parse(Carbon::now()->format('Y-m-d'))->timestamp)->count();
        if ($times >= DummyJotting::DAILY_MAX_RECORDS){
            throw new BadRequestException('每日最多记录'.DummyJotting::DAILY_MAX_RECORDS.'篇随笔', Response::HTTP_FORBIDDEN);
        }
        $data = $request->post(['content', 'score']);

        Db::startTrans();
        try {
            $this->user->dummy->score->save(['total_score' => $this->user->dummy->score->total_score + (int)$data['score']]);
            $jotting =$this->user->dummy->jottings()->save(array_merge($data, ['user_id' => $this->user->id]));
            Db::commit();
            DummyCache::removeUserDummyById($this->user->id);
            return $jotting;
        } catch (\Exception $exception){
            Db::rollback();
            throw new ServiceUnavailableException('系统错误，请稍后再试');
        }
    }

    public function delete(int $id)
    {
        if (!$this->user->dummy){
            throw new BadRequestException('请先创建虚拟对象', Response::HTTP_FORBIDDEN);
        }
        $jotting = $this->user->dummy->jottings()->find($id);
        if (!$jotting){
            throw new ModelNotFoundException('未找到该随笔信息');
        }
        DummyCache::removeUserDummyById($this->user->id);
        return $jotting->delete();
    }
}
